package com.heeexy.example.service;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.config.exception.CommonJsonException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import yinwei.bo.base.util.JwtUtils;
import yinwei.bo.common.Constants.Constans;
import yinwei.bo.common.entry.uList;
import yinwei.bo.common.util.RedisCache;
import yinwei.bo.common.util.StringUtils;
import yinwei.bo.common.util.uuid.Idutils;

import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    private JSONObject resultJson;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;

    @Resource
    private UserService userService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        System.out.println(uuid);
        String verifyKey = Constans.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CommonJsonException("验证码不能为空");
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CommonJsonException("验证码错误");
        }
        uList ulist=userService.findUser(username);
        if (StringUtils.isNull(ulist)){
            throw new CommonJsonException("账号错误");
        }
        if (!password.equals(ulist.getPassword())){
            throw new CommonJsonException("密码错误");
        }
        String uuid1 = ulist.getAccout();
        String userKey = tokenService.getTokenKey(uuid1);
        redisCache.setCacheObject(userKey, ulist, 6000, TimeUnit.MINUTES);

        /*Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        subject.login(token);*/


        /*// 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());*/
        // 生成token
        System.out.println("ulist_id"+ulist.getUlistId());
        return JwtUtils.createToken(Long.valueOf(ulist.getUlistId()),ulist.getAccout());
    }

    /**
     * 记录登录信息
     */
    /*public void recordLoginInfo(SysUser user)
    {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);
    }*/
}
